package cn.yuxiaoyuan.system.controller;

import cn.yuxiaoyuan.annotation.PreAuthorize;
import cn.yuxiaoyuan.system.domain.Role;
import cn.yuxiaoyuan.system.query.RoleQuery;
import cn.yuxiaoyuan.system.service.RoleService;
import cn.yuxiaoyuan.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @PreAuthorize(sn = "role:findById",name = "根据id查询角色",descs = "根据id查询角色")
    @GetMapping("/{id}")
    public R findById(@PathVariable("id") Long id) {
        return R.ok(roleService.findById(id));
    }

    @PreAuthorize(sn = "role:findAll",name = "查询所有角色",descs = "查询所有角色")
    @GetMapping
    public R findAll() {
        return R.ok(roleService.findAll());
    }

    @PreAuthorize(sn = "role:deleteById",name = "根据id删除角色",descs = "根据id删除角色")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable("id") Long id) {
        roleService.deleteById(id);
        return R.ok();
    }

    @PreAuthorize(sn = "role:deleteAll",name = "根据ids删除角色",descs = "根据ids删除角色")
    @PostMapping("/deleteAll")
    public R batchDelete(@RequestBody List<Long> ids) {
        roleService.batchDelete(ids);
        return R.ok();
    }

    @PreAuthorize(sn = "role:add",name = "添加和修改角色",descs = "添加和修改角色")
    @ApiOperation("添加和修改")
    @PostMapping
    public R add(@RequestBody Role role) {
        if (role.getId() == null) {
            roleService.add(role);
        } else {
            roleService.update(role);
        }
        return R.ok();
    }

    @PreAuthorize(sn = "role:getPage",name = "角色的分页查询",descs = "角色的分页查询")
    @PostMapping("/page")
    public R getPage(@RequestBody RoleQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<Role> roles = roleService.queryPage(query);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return R.ok(pageInfo);
    }
}
